package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) {
        //创key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //检验有没有key
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            //0.检查手机号是否已经发送了，并且在有效期内！在的话，告诉他发送频繁
            /**
             * 方案1： 查看验证码是否存在，存在，就不能发送！ 有效期 == 前端的倒计时
             *        根据key获取值，有就不能发，没有，就可以发！！
             * 方案2： 前端倒计时60秒！60秒后可以重复发送，验证码的有效期是300秒！！
             *        常量1： 总时间300  1  场景2： 间隔时间60 2
             *        redisTemplate获取剩余的时间 3
             *        if(1-3 > 2){可以发送} else{不可以发送}
             */
            //3.剩余时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //1.600s
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //2.60s
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            if (appLoginCodeTtlSec - expire < appLoginCodeResendTimeSec) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //生成验证码，6位数字
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString();
        System.out.println("验证码 = " + code);
        //2.存储到redis中【有效期】
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
        //3.发送验证码
    }

    @Override
    public String login(LoginVo loginVo) {
        //接收前端手机号和验证码
        //对比验证码是否正确
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        if (code == null || !code.equals(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //正确查看登录或注册
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        //手机号去数据库查询没有创建新的
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            //佚名+手机号后四位
            userInfo.setNickname("佚名" + loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }
        //判断用户是否可用
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //可用创建jwt-》token-》返回
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getNickname());
        return token;
    }

    @Override
    public UserInfoVo info(String accessToken) {
        //1.解析userId
        Integer userId = (Integer) JwtUtil.parseToken(accessToken).get("userId");
        //2.根据userId查询
        UserInfo userInfo = userInfoService.getById(userId);
        //3.封装vo
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
